package cn.kgc.tangcco.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李昊哲
 * @Description
 * @create 2021/1/25 9:44
 */
@WebFilter("*.action")
public class CORS implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 处理中文乱码
        // 处理post请求的中文乱码
        req.setCharacterEncoding("utf-8");
        // 处理响应的字符集中文乱码
        resp.setCharacterEncoding("utf-8");
        // 处理浏览器字符集中文乱码
        resp.setContentType("text/html;charset=utf-8");
        String method = req.getMethod();
        System.out.println("请求方式 >>>  " + method);
        if ("OPTIONS".equalsIgnoreCase(method)) {
            resp.setHeader("Access-Control-Allow-Origin", "*");
            resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            resp.setHeader("Access-Control-Max-Age", "3600");
            resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authentication, token, callback");
            resp.addHeader("Access-Control-Allow-Credentials", "false");
            return;
        }
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authentication, token, callback");
        resp.addHeader("Access-Control-Allow-Credentials", "false");
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }
}
